using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.APPLications.Commands.TraceabilityInfoshow;
using Traceability.API.Dtos;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.TraceabilityInfoshow
{
    /// <summary>
    /// 获取所有溯源信息查询处理程序（不带条件，仅分页）
    /// </summary>
    public class GetAllTraceabilityInfoQueryHandler : IRequestHandler<GetAllTraceabilityInfoQuery, APIResult<PagedResultDto<TraceabilityInfoDto>>>
    {
        private readonly IBaseRepository<TraceabilityInfo> _traceabilityRepository;
        private readonly IBaseRepository<Products> _productRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="traceabilityRepository">溯源信息仓储</param>
        /// <param name="productRepository">商品仓储</param>
        public GetAllTraceabilityInfoQueryHandler(
            IBaseRepository<TraceabilityInfo> traceabilityRepository,
            IBaseRepository<Products> productRepository)
        {
            _traceabilityRepository = traceabilityRepository;
            _productRepository = productRepository;
        }

        /// <summary>
        /// 处理查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>查询结果</returns>
        public async Task<APIResult<PagedResultDto<TraceabilityInfoDto>>> Handle(GetAllTraceabilityInfoQuery request, CancellationToken cancellationToken)
        {
            var result = new APIResult<PagedResultDto<TraceabilityInfoDto>>();

            try
            {
                // 构建查询 - 查询所有记录（已改为物理删除）
                var query = _traceabilityRepository.GetAll();

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页
                var pagedItems = await query
                    .OrderByDescending(t => t.CreatedTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 获取所有相关的商品ID
                var productIds = pagedItems.Select(t => t.ProductId).Distinct().ToList();

                // 获取商品信息
                var products = await _productRepository.GetAll()
                    .Where(p => productIds.Contains(p.ProductId))
                    .ToDictionaryAsync(p => p.ProductId, p => p.ProductName, cancellationToken);

                // 转换为DTO
                var dtoItems = pagedItems.Select(t => new TraceabilityInfoDto
                {
                    TraceabilityId = t.TraceabilityId,
                    ProductId = t.ProductId,
                    ProductName = products.TryGetValue(t.ProductId, out var name) ? name : "未知商品",
                    ProductionBatch = t.ProductionBatch,
                    ShelfLife = t.ShelfLife,
                    ProductionLicenseNumber = t.ProductionLicenseNumber,
                    ManufacturerName = t.ManufacturerName,
                    InformationCompleteness = t.InformationCompleteness,
                    PhotoUrl = t.PhotoUrl,
                    CreatedBy = t.CreatedBy,
                    CreatedTime = t.CreatedTime,
                    ModifiedBy = t.ModifiedBy ?? string.Empty,
                    ModifiedTime = t.ModifiedTime,
                    IsDeleted = t.IsDeleted
                }).ToList();

                // 构建分页结果
                var pagedResult = new PagedResultDto<TraceabilityInfoDto>
                {
                    TotalCount = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    Items = dtoItems
                };

                result.Code = APIEnum.查询成功;
                result.Message = "查询成功";
                result.Data = pagedResult;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.查询失败;
                result.Message = $"查询失败: {ex.Message}";
            }

            return result;
        }
    }
} 